package com.googlecode.wmlynar.springconfgraph;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * Goal which touches a timestamp file.
 * 
 * @author Wojciech Mlynarczyk
 * 
 * @goal generate
 * 
 * @phase process-sources
 */
public class GenerateMojo extends AbstractMojo {
	
	/**
	 * Location of the output file.
	 * 
	 * @parameter expression="${project.build.directory}"
	 * @required
	 */
	private File outputDirectory;

	/**
	 * Location of the output file.
	 * 
	 * @parameter expression="${spring.configuration.graph.showUtilityClasses}" default-value="true"
	 * @required
	 */
	private boolean showUtilityClasses;
	
	/**
	 * Location of the file.
	 * 
	 * @parameter
	 * @required
	 */
	ArrayList<String> folders = new ArrayList<String>();
	
	public void execute() throws MojoExecutionException {
		GraphStringBuilder.includeUtility = showUtilityClasses;
		String output = GraphStringBuilder.buildArchitectureString(folders);
		writeToFile(output);
	}

	private void writeToFile(String output) throws MojoExecutionException {
		File f = outputDirectory;

		if (!f.exists()) {
			f.mkdirs();
		}
		
		File f2 = new File(f, "spring_configuration_graph.txt");
		PrintWriter out = null;
		try {
			out = new PrintWriter(f2);
			out.println(output);
		} catch (IOException e) {
			throw new MojoExecutionException("Error creating file " + f2, e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
